import {cosModel} from '../api/models'
const COS = require('cos-js-sdk-v5');
export default {
  data() {
    return {
      uploading: false,
      uploadPercentage: 0,
      speed: ''
    }
  },
  methods: {
    onUpload(pos, file, success, error) {
      let cos = new COS({
        getAuthorization: function (options, callback) {
          cosModel.getSTS((res) => {
            console.log(res)
            let data = res.data
            let credentials = data && data.credentials;
            if (!data || !credentials) error('cos预签名失败')
            callback({
              TmpSecretId: credentials.tmpSecretId,
              TmpSecretKey: credentials.tmpSecretKey,
              XCosSecurityToken: credentials.sessionToken,
              // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
              StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
              ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
              // ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
            })
          })
        }
      });
      let date = new Date()
      cos.sliceUploadFile({
        Bucket: 'os-image-bj-1258514725', /* 必须 */
        Region: 'ap-beijing',     /* 存储桶所在地域，必须字段 */
        // todo
        Key: pos + '/' + date.getFullYear() + '/' + date.getMonth() + '/' + date.getDate() + '/' + date.getTime() + "." + file.name.split('.').pop(),              /* 必须 */
        Body: file,                /* 必须 */
        onTaskReady: (taskId) => {                   /* 非必须 */
          console.log('onTaskReady:', taskId);
        },
        onHashProgress: (progressData) => {       /* 非必须 */
          console.log('progras', progressData)
        },
        onProgress: (progressData) => {           /* 非必须 */
          console.log('onProgress', progressData)
          this.uploading = true
          this.uploadPercentage = parseInt(progressData.percent * 100)
          this.speed = (progressData.speed / 1024 / 1024).toFixed(2) + 'M/s'
        }
      }, (err, data) => {
        if (err) {
          error(err)
        }else{
          success(data)
        }
      });
    }
  }
}